package com.atguigu.crowd.filter;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;

import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.entity.vo.MemberLoginVO;
import com.atguigu.crowd.util.JudgeResourceAccess;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

//登录资源过滤
@Component
public class CrowdAccessFilter extends ZuulFilter {

	@Override
	public boolean shouldFilter() {
		//获取servletPath
		RequestContext currentContext = RequestContext.getCurrentContext();
		HttpServletRequest request = currentContext.getRequest();
		String servletPath = request.getServletPath();
		//判断是否为路径资源
		//特殊的四个路径带动态参数：列如/project/get/project/detail/18
		
		if (servletPath.startsWith("/project/get/project/detail")
			||servletPath.startsWith("/project/get/project/orderby/page")
			||servletPath.startsWith("/project/get/project/by/status/page")
			||servletPath.startsWith("/project/get/project/by/type/page")
			) {
			return false;
		}
		boolean resResult = JudgeResourceAccess.PASS_RES_SET.contains(servletPath);
		if (resResult) {//是功能路径
			//不过滤,false则不执行run方法
			return false;
			
		}
		//判断是否为静态资源
		boolean staticResult = JudgeResourceAccess.judgeCurrentPathIsStaticRes(servletPath);
		if (staticResult) {//是静态资源
			//放行
			return false;
		}
		//执行run方法，进行过滤
		return true;
	}
	//需要登录
	@Override
	public Object run() throws ZuulException {
		//从session中获取登录用户、
		RequestContext currentContext = RequestContext.getCurrentContext();
		HttpServletRequest request = currentContext.getRequest();
		HttpSession session = request.getSession();
		MemberLoginVO loginMember = (MemberLoginVO)session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
		//判断是否登录
		if (loginMember==null) {
			//未登录，则重定向到登录页面
			HttpServletResponse response = currentContext.getResponse();
			//将提示信息存入session中
			session.setAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_ACCESS_FORBIDEN);
			try {
				//重定向到auth-consumer工程的登录页面
				response.sendRedirect("/auth/member/to/login/page");
			} catch (IOException e) {
				e.printStackTrace();
			}
		
		}
		return null;
	}

	@Override
	public int filterOrder() {
		
		return 0;
	}

	@Override
	public String filterType() {
		
		return "pre";
	}

}
